Class

A Scala class is a template for Scala objects. That means, that a class defines what information obje cts of that class holds, and what behavior (methods) it exposes. A class can contain information about Fields, Constructors,Methods,Superclasses (inheritance) Interfaces implemented by the class etc.

Here is the class definition

class myClass{
// methods and attributes
}

A class can in Scala inherits only one parent class, which means Scala does not support multiple inheritances. However, it can be achieved with the use of Traits. Finally, the body of a class in Scala is surrounded by curly braces {}.

Fields
A field is a variable that is accessible inside the whole object. This is contrast to local variables, which are only accessible inside the method in which they are declared. Here is a simple field declaration:

class myClass{
val x=5
}

This declaration defines a field of type Int and initializes it to the value 0.

Object
A class is a blueprint for objects. Once you define a class, you can create objects from the class blueprint with the keyword new. Through the object you can use all functionalities of the defined class.

val ob = new myClass
println(ob.x)

// Name of the class is Car

class Car
{
// Class variables
var make: String = "BMW"
var model: String = "X7"
var fuel: Int = 40

// Class method
def Display()
{
println("Make of the Car : " + make);
println("Model of the Car : " + model);
println("Fuel capacity of the Car : " + fuel);
}
}
object demo
{
// Main method
def main(args: Array[String])
{
// Class object
var obj = new Car();
obj.Display();
}
}

Calculate the area

package area
class reactangle( val length :Int,width:Int)
{
 var result= length * width
}

object polygon {
  def main(args :Array[String]) =  {
  val rect = new reactangle(20,30)
  println(rect.result)
  }
}

Access the private member of class

package area

class reactangle(private var length :Int,width:Int)
{
 var result= length * width
}

object polygon {
  def main(args :Array[String]) =  {
  val rect = new reactangle(20,30)
  println(rect.result)
  println(rect.length)
  }
}

No comments:

Post a Comment